package entityDAOs;

import static org.hibernate.criterion.Example.create;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import interfaces.IBaseHibernateDAO;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import entities.Departament;
import entities.HibernateSessionFactory;


/**
 * Data access object (DAO) for domain model
 * @author MyEclipse Persistence Tools
 * @param <E>
 */
public class BaseHibernateDAO<E, PK extends Serializable> implements IBaseHibernateDAO {
	
	private static Logger log;
	private Class<E> entityClass;
	
	public BaseHibernateDAO() {
		this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		this.log = LoggerFactory.getLogger(entityClass);
	}
	
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}
	
	public void save(E transientInstance) {
		log.debug("saving "+ entityClass.getSimpleName() +" instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(E persistentInstance) {
		log.debug("deleting "+entityClass.getSimpleName()+" instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	public E findById(PK id) {
		log.debug("getting "+entityClass.getSimpleName()+" instance with id: " + id.toString());
		try {
			E instance = (E) getSession().get(entityClass.getName(), id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public List<E> findByExample(E instance) {
		log.debug("finding "+entityClass.getSimpleName()+" instance by example");
		try {
			List<E> results = (List<E>) getSession()
					.createCriteria(entityClass.getName())
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding "+entityClass.getSimpleName()+" instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from "+entityClass.getSimpleName()+" as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	
	public List findAll() {
		log.debug("finding all "+entityClass.getSimpleName()+" instances");
		try {
			String queryString = "from "+entityClass.getSimpleName();
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public E merge(E detachedInstance) {
		log.debug("merging "+entityClass.getSimpleName()+" instance");
		try {
			E result = (E) getSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(E instance) {
		log.debug("attaching dirty "+entityClass.getSimpleName()+" instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(E instance) {
		log.debug("attaching clean "+entityClass.getSimpleName()+" instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}